package com.sunducation.wts.savestate

import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.SavedStateViewModelFactory
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_main.*
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import androidx.annotation.NonNull
import androidx.appcompat.app.AppCompatActivity
import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryOwner


/*
* 虽然viewModel要比onSaveInstanceState简单，但是viewModel只能在屏幕旋转和语言切换后（即配置变更时）的页面重建维持数据，
* 当页面意外销毁时数据无法恢复（viewModel也会重建），而这点onSaveInstanceState可以做到。
* 关于意外销毁，我们暂且理解成非配置变更引起的销毁重建，比如内存不足等场景。
*
* ViewModel是保存activitiy中的数据 当系统屏幕反转或者按下home时activity会被销毁重新创建，
* 这时候我们的数据会被重新初始化，所以我们要用ViewModel来保存当前的状态（当然按下返回键和结束进程不会保存）
* */
class MainActivity : AppCompatActivity(), SavedStateRegistryOwner {

    private lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Obtain the ViewModel with SavedStateViewModelFactory
        viewModel = ViewModelProvider(this, SavedStateViewModelFactory(application, this@MainActivity)).get(MainViewModel::class.java)

        // Set the value manually during creation
        manualText.setText(viewModel.manualText)
        manualValue.setText(viewModel.manualText)

        // Observe the livedata
        viewModel.liveDataText.observe(this, Observer {
            liveDataText.setText(it)
            liveDataValue.setText(it)
        })

        // Save the values
        // This is done manually for the demo
        button.setOnClickListener {
            viewModel.manualText = manualText.text.toString()
            viewModel.liveDataText.value = liveDataText.text.toString()
        }
    }




}
